/**
 *
 */
package hichecker.ui.components.custom_table.table_cell_editor;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.EventObject;

import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.JTable;
import javax.swing.JTextField;

/**
 *
 */
abstract public class AbstractTableCellEditor extends DefaultCellEditor{

	protected JTextField comp;
	protected boolean resetText;

	public AbstractTableCellEditor() {
		super(new JTextField());
		comp = (JTextField) getComponent();
		comp.setBorder(BorderFactory.createLineBorder(Color.BLACK));
	}

	@Override
	public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
			int row, int column) {
		comp.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		comp.setText(resetText ? "" : value == null ? "" : "" + value);

		return comp;
	}

	@Override
	public Object getCellEditorValue() {
		return comp.getText();
	}

	@Override
	public boolean isCellEditable(EventObject anEvent) {
		resetText = false;

		// It's a mouseevent, so count the clicks
	    if (anEvent instanceof MouseEvent) {
			return ((MouseEvent)anEvent).getClickCount() >= clickCountToStart;
	    }

	    // It's a keyevent, so check if it's a key that should start editing
	    if (anEvent instanceof KeyEvent) {

	    	// Get the events key
	    	int keyCode = ((KeyEvent) anEvent).getKeyCode();
	    	char keyChar = ((KeyEvent) anEvent).getKeyChar();

	    	// Convert character to lower case by first creating a string out of it
	    	keyChar = ("" + keyChar).toLowerCase().charAt(0);

	    	// F2 allowed
	    	if (keyCode == KeyEvent.VK_F2) {
	    		return true;
	    	}

	    	// Keycode is unknown so check if we can at least find the keyChar
	    	if (keyCode == 0 && (keyChar == 'ä' || keyChar == 'ö' || keyChar == 'ü')) {
	    		resetText = true;
	    		return true;
	    	}

			// Control characters disallowed
			if (keyCode < 32 || keyCode == KeyEvent.VK_WINDOWS
					|| keyCode == KeyEvent.VK_CONTEXT_MENU || keyCode == KeyEvent.VK_SCROLL_LOCK
					|| keyCode == KeyEvent.VK_NUM_LOCK || keyCode == KeyEvent.VK_META
					|| (keyCode >= KeyEvent.VK_F1 && keyCode <= KeyEvent.VK_F12))
				return false;

	    	// all other keys are allowed
	    	resetText = true;
	    	return true;
	    }

	    // All other events are also allowed
	    return false;
	}

	@Override
	public boolean stopCellEditing() {
		boolean valid = isValidInput();
		if (!valid) {
			comp.setBorder(BorderFactory.createLineBorder(Color.RED));
			return false;
		}
		comp.setText(getModifiedInput());
		fireEditingStopped();
		return true;
	}

	abstract public boolean isValidInput();

	abstract protected String getModifiedInput();

}
